package com.luozongyao.utils;

import com.alibaba.fastjson.JSON;
import com.luozongyao.commons.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class TokenInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info(token);

        if (StringUtils.hasText(token)) {
            response.setContentType("application/json;charset=UTF-8");
            try {
                JwtUtil.verifyToken(token);
            }
            catch (Exception e) {
                response.getWriter().write(JSON.toJSONString(R.error().message("无效的token，请不要尝试进行任何的非法操作！")));
                return false;
            }
        }
        return true;
    }
}
